package controller

import (
	"fmt"
	"net"
)

/**
 * Package controller
 * @File : net.go
 * @Description : 获取服务地址
 * @Author : 吴概
 * @Date : 2023/2/21 10:59
 */

// GetIPv4Address 获取并返回IPv4地址
func GetIPv4Address() string {
	var addr = ""
	//获取所有网卡
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Println("net.Interfaces failed, err:", err.Error())
	}
	for i := 0; i < len(netInterfaces); i++ {
		if (netInterfaces[i].Flags & net.FlagUp) != 0 {
			addrs, _ := netInterfaces[i].Addrs()
			for _, address := range addrs {
				if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
					if ipnet.IP.To4() != nil {
						addr = ipnet.IP.To4().String()
						addr += ":8080"
					}
				}
			}
		}
	}
	return addr
}

// GetCompleteIpv4Address 获取带“http://"的IPv4地址，用于上传视频时保存视频地址
func GetCompleteIpv4Address() string {
	addr := GetIPv4Address()
	if addr == "" {
		fmt.Println("未初始化")
		return ""
	}
	return "http://" + addr + "/"
}
